﻿using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace Web.HelperClasses
{
    public class HttpClient
    {
        //todo: обрабатывать ответы от сервера
    	public HttpClient()
    	{
			ServicePointManager.Expect100Continue = false;
    	}

        public XElement Post(string addr, string contentType, byte[] bytes)
        {
            return XElement.Load(Intercourse(addr, "POST", contentType, bytes));
        }

        public XElement Put(string addr, string contentType, byte[] bytes)
        {
            return XElement.Load(Intercourse(addr, "PUT", contentType, bytes));
        }

        public XElement Get(string addr)
        {
            return XElement.Load(Intercourse(addr, "GET"));
        }

        public void Delete(string addr)
        {
            Intercourse(addr, "DELETE");
        }

        private Stream Intercourse(string addr, string method, string contentType = null, byte[] bytes = null)
        {
            var req = (HttpWebRequest)WebRequest.Create(addr + "?oauth_token=" + OAuth.OAuthToken);
			
            req.Method = method;
            req.Headers[HttpRequestHeader.Authorization] = "OAuth " + OAuth.OAuthToken;
            
            if (bytes != null)
            {
                req.ContentType = contentType;
                req.ContentLength = bytes.Length;
                
                var reqStream = req.GetRequestStream();
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            var response = req.GetResponse();
            return response.GetResponseStream();
        }

        public XElement Post(string addr, string contentType, string str)
        {
            return Post(addr, contentType, Encoding.UTF8.GetBytes(str));
        }

        public XElement Put(string addr, string contentType, string str)
        {
            return Put(addr, contentType, Encoding.UTF8.GetBytes(str));
        }
    }
}